package com.bci.pwtz.controller.app;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.ObjResponse;
import com.bci.pwtz.common.remote.ReturnCode;
import com.bci.pwtz.common.remote.req.CompanyUserAuditIdReq;
import com.bci.pwtz.common.remote.req.CompanyUserAuditReq;
import com.bci.pwtz.controller.AbstractController;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.model.Company;
import com.bci.pwtz.mysql.model.CompanyRole;
import com.bci.pwtz.mysql.model.CompanyUser;
import com.bci.pwtz.mysql.model.CompanyUserAudit;
import com.bci.pwtz.mysql.model.CompanyUserRole;
import com.bci.pwtz.mysql.model.UserCompanyRef;
import com.bci.pwtz.service.CompanyRoleService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.CompanyUserAuditService;
import com.bci.pwtz.service.CompanyUserService;
import com.bci.pwtz.service.MessageService;
import com.bci.pwtz.service.UserCompanyRefService;
@Controller
@RequestMapping("/api/companyuseraudit")
public class CompanyUserAuditAppController extends AbstractController
{
@Autowired
CompanyUserAuditService companyUserAuditService;

@Autowired
CompanyService companyService;
@Autowired
UserCompanyRefService userCompanyRefService;
@Autowired
MessageService messageService;
@Autowired
private CompanyRoleService     companyRoleService;
@Autowired
private CompanyUserService     companyUserService;
/**
 * 添加用户申请
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月26日-下午4:48:04<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping(value="/add",method=RequestMethod.POST)
@ResponseBody
public ObjResponse<CompanyUserAudit> add(HttpServletRequest request){
    CompanyUserAuditReq req=null;
    ObjResponse<CompanyUserAudit> resp=new ObjResponse<CompanyUserAudit>();
    try{
        req=getJsonToObj(request,CompanyUserAuditReq.class);
        if(req==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空错误");
            return resp;
        }
        if(req.getCompanyUserAudit()==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("参数错误");
            return resp;
        }
        if(req.getSecretKey()==null){
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("秘钥为空");
            return resp;
        }
        if(req.getTimestamp()==null){
            resp.setReturnCode(ReturnCode.OTHER_ERROR);
            resp.setReturnMsg("时间戳为空错误");
            return resp;
        }
        if(!validateSecretKey(req.getSecretKey(),req.getTimestamp())){
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("秘钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(StringUtils.isBlank(req.getToken())){
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(!validateToken(req.getToken(), req.getUserId())){
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        int joinCompanyNumByUserId=userCompanyRefService.selectJoinCompanyNumByUserId(req.getUserId());
        if(joinCompanyNumByUserId>=PwtzConstants.MAX_JOIN_COMPANY_COUNT){
            resp.setReturnCode(ReturnCode.OTHER_ERROR);
            resp.setReturnMsg("加入公司数已达最大，不能再加入");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        CompanyUserAudit audit=companyUserAuditService.add(req.getCompanyUserAudit());
        boolean isVip =  companyService.isVip(audit.getCompanyId());
        if(!isVip){
            int companyUsers = userCompanyRefService.selectCompanyUsers(audit.getCompanyId());
            if(companyUsers>=PwtzConstants.THE_TRIAL_USERS_COUNT){
                resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
                resp.setReturnMsg("所要加入的单位员工数已满");
                resp.setTimestamp(req.getTimestamp());
                return resp;
            }
        }
        if(audit !=null){
            resp.setReturnCode(ReturnCode.SUCCESS);
            if(audit.getResult()==0){
                resp.setReturnMsg("审核中，请勿重复申请");
            }else{
                resp.setReturnMsg("添加审核成功");
                companyService.sendJoinCompanyValidateSms(audit.getCompanyUserId(), audit.getCompanyId(), audit.getAuditId());
            }
            resp.setObj(audit);
            resp.setTimestamp(req.getTimestamp());
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("添加审核调用接口失败");
            resp.setTimestamp(req.getTimestamp());
        }
    }catch(PwtzDatabaseException e){
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }catch(Exception e){
        resp.setReturnCode(ReturnCode.OTHER_ERROR);
        resp.setReturnMsg("系统错误");
        req.setTimestamp(resp.getTimestamp());
    }
    return resp;
}
/**
 * 审核申请请求
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月26日-下午4:48:39<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping("/check")
@ResponseBody
public ObjResponse<Integer> check(HttpServletRequest request){
    CompanyUserAuditIdReq req=null;
    ObjResponse<Integer> resp=new ObjResponse<Integer>();
    try{
        req=getJsonToObj(request,CompanyUserAuditIdReq.class);
        if(req==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空错误");
            return resp;
        }
        if(req.getAuditId()==null||req.getResult()==0){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("参数错误");
            return resp;
        }
        if(req.getSecretKey()==null){
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("秘钥为空");
            return resp;
        }
        if(req.getTimestamp()==null){
            resp.setReturnCode(ReturnCode.OTHER_ERROR);
            resp.setReturnMsg("时间戳为空错误");
            return resp;
        }
        if(!validateSecretKey(req.getSecretKey(),req.getTimestamp())){
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("秘钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(StringUtils.isBlank(req.getToken())){
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(!validateToken(req.getToken(), req.getUserId())){
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        CompanyUserAudit audit=companyUserAuditService.load(req.getAuditId());
        if(audit!=null){
            if(audit.getResult()==1){
                int result=companyUserAuditService.check(req.getAuditId(), req.getResult());
                if(result>0){
                    resp.setReturnCode(ReturnCode.SUCCESS);
                    resp.setReturnMsg("审核完成");
                    resp.setTimestamp(req.getTimestamp());
                    resp.setObj(req.getResult());
                    if(req.getResult()==2){
                        CompanyUserAudit rtAudit=companyUserAuditService.load(req.getAuditId());
                        Long userId=rtAudit.getCompanyUserId();
                        Long companyId=rtAudit.getCompanyId();
                        if(companyId>0){
                            UserCompanyRef ref=new UserCompanyRef();
                            ref.setCompanyId(companyId);
                            ref.setCompanyUserId(userId);
                            companyUserService.addUserCompanyRef(ref);
                            CompanyUser user=companyUserService.load(userId);
                            if(user.getLastCompanyId()==null){
                                user.setLastCompanyId(companyId);
                                companyUserService.update(user);
                            }
                        }
                        CompanyRole companyRole=companyRoleService.selectDefault(companyId);
                        if(companyRole!=null){
                            CompanyUserRole ref = new CompanyUserRole();
                            ref.setCompanyRoleId(companyRole.getCompanyRoleId());
                            ref.setCompanyUserId(userId);
                            companyUserService.addCompanyUserRole(ref);
                        }
                        if(rtAudit!=null){
                            Company rtCompany=companyService.load(rtAudit.getCompanyId());
                            if(rtCompany!=null){
                                messageService.sendAuditSmsAndMsg(rtAudit.getCompanyUserId(),req.getAuditId(), PwtzConstants.AUDIT_SUCCESS_MSG,rtCompany.getCompanyName());
                            }
                        }
                    }
                }
            }else if(audit.getResult()==2){
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("审核完成");
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(audit.getResult());
            }else{
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("审核完成");
                resp.setTimestamp(req.getTimestamp());
                resp.setObj(audit.getResult());
            }
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("审核调用接口失败");
            resp.setTimestamp(req.getTimestamp());
            resp.setObj(0);
        }
    }catch(PwtzDatabaseException e){
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }catch(Exception e){
        resp.setReturnCode(ReturnCode.OTHER_ERROR);
        resp.setReturnMsg("系统错误");
        req.setTimestamp(resp.getTimestamp());
    }
    return resp;
}
}
